
package com.shai.wool.activity.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.shai.wool.activity.entity.ActivityInfoVO;
import com.shai.wool.activity.param.ActivityInfoParam;
import com.shai.wool.activity.service.ActivityInfoService;
import com.shai.wool.common.controller.BaseController;
import com.shai.wool.common.param.SessionUserInfo;
import com.shai.wool.sensitiveword.SensitiveWordUtils;

/**
 * 活动信息Controller
 *
 * @author 朱国军
 * @since 1.0
 * @version 2015年12月27日 朱国军
 */
@Controller
public class ActivityInfoController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(ActivityInfoController.class);

    @Autowired
    private ActivityInfoService activityInfoService;

    private final static String LIST_PAGE = "/activity/activity_list_ajax";

    private final static String VIEW_PAGE = "/activity/activity_view";

    private final static String UPDATE_PAGE = "/activity/activity_edit";

    private static final String MY_LIST_PAGE = "/account/my_activity";
    
    @RequestMapping(value = "/check/activity/toInsert")
    public ModelAndView intoInsert() {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        ActivityInfoVO activityInfoVO = new ActivityInfoVO();
        resultMap.put("activity", activityInfoVO);
        return new ModelAndView(UPDATE_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/check/activity/toUpdate/{id}")
    public ModelAndView intoUpdate(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        ActivityInfoVO activityInfoVO = activityInfoService.findById(id);
        resultMap.put("activity", activityInfoVO);
        return new ModelAndView(UPDATE_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/check/activity/update", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String update(ActivityInfoVO activity) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        if (SensitiveWordUtils.isContaintSensitiveWord(activity.getActivityDetail(), 1)) {
            resultMap.put("result", false);
            resultMap.put("message", "活动详情中包含敏感词汇" + SensitiveWordUtils.getSensitiveWord(activity.getActivityDetail(), 1) + "，请检查后再保存");
            return JSONObject.toJSONString(resultMap);
        }

        if (SensitiveWordUtils.isContaintSensitiveWord(activity.getActivityName(), 1)) {
            resultMap.put("result", false);
            resultMap.put("message", "活动名称中包含敏感词汇" + SensitiveWordUtils.getSensitiveWord(activity.getActivityName(), 1) + "，请检查后再保存");
            return JSONObject.toJSONString(resultMap);
        }
        
        if (SensitiveWordUtils.isContaintSensitiveWord(activity.getPlatformName(), 1)) {
            resultMap.put("result", false);
            resultMap.put("message", "平台名称中包含敏感词汇" + SensitiveWordUtils.getSensitiveWord(activity.getPlatformName(), 1) + "，请检查后再保存");
            return JSONObject.toJSONString(resultMap);
        }
        
        if (SensitiveWordUtils.isContaintSensitiveWord(activity.getActivityUrl(), 1)) {
            resultMap.put("result", false);
            resultMap.put("message", "活动连接中包含敏感词汇" + SensitiveWordUtils.getSensitiveWord(activity.getActivityUrl(), 1) + "，请检查后再保存");
            return JSONObject.toJSONString(resultMap);
        }

        try {
            Integer affectCount = 0;
            
            if (activity != null && StringUtils.isNotBlank(activity.getActivityId())) {
                activity.setActivityEndTime(new Date(DateUtils.addDays(activity.getActivityEndTime(), 1).getTime() - 1000));
                affectCount = activityInfoService.update(activity);
            } else if (activity != null) {
                activity.setActivityId(UUID.randomUUID().toString());
                activity.setPublishUser(seUser.getUserId());
                activity.setDataStatus(0);
                activity.setActivityEndTime(new Date(DateUtils.addDays(activity.getActivityEndTime(), 1).getTime() - 1000));
                affectCount = activityInfoService.insert(activity);
            }
            
            if (affectCount != null && affectCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "新增或修改活动信息成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "新增或修改活动信息失败");
            }
        } catch (Exception e) {
            logger.error("新增或修改活动信息出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "新增或修改活动信息出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }
    
    @RequestMapping(value = "/admin/activity/delete/{id}", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String delete(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Integer deleteCount = activityInfoService.delete(id);
            if (deleteCount != null && deleteCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "删除活动信息成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "删除活动信息失败");
            }
        } catch (Exception e) {
            logger.error("删除活动信息出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "删除活动信息出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }

    @RequestMapping(value = "/uncheck/activity/list", produces = "text/html;charset=utf-8;")
    @ResponseBody
    public ModelAndView queryList(ActivityInfoParam activityInfoParam) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        // 设置系统时间，查询进行中的活动
        activityInfoParam.setSystemTime(new Date(System.currentTimeMillis()));
        List<Map<String, Object>> dataList = activityInfoService.queryByPage(activityInfoParam);
        resultMap.put("activityList", dataList);
        resultMap.put("queryMap", activityInfoParam);
        return new ModelAndView(LIST_PAGE, resultMap);
    }

    @RequestMapping(value = "/account/activity/list", produces = "text/html;charset=utf-8;")
    @ResponseBody
    public ModelAndView queryMyList(ActivityInfoParam activityInfoParam) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");

        activityInfoParam.setPublishUser(seUser.getUserId());
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<Map<String, Object>> dataList = activityInfoService.queryByPage(activityInfoParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", activityInfoParam);
        return new ModelAndView(MY_LIST_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/uncheck/activity/view/{id}")
    public ModelAndView viewConfigInfo(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        ActivityInfoVO activityInfoVO = activityInfoService.findById(id);
        resultMap.put("activity", activityInfoVO);
        resultMap.put("discussType", 1);
        resultMap.put("discussTargetId", activityInfoVO.getActivityId());
        return new ModelAndView(VIEW_PAGE, resultMap);
    }
}
